package com.jiyinit.web.core.business.controller;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.core.framework.base.util.DateUtil;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.business.dto.MessagePageRequest;
import com.jiyinit.web.core.business.dto.NoticePageRequest;
import com.jiyinit.web.core.business.dto.NoticeRequest;
import com.jiyinit.web.core.business.dto.UserRequest;
import com.jiyinit.web.core.business.entity.TabCoreNoticeEntity;
import com.jiyinit.web.core.business.entity.TabCoreOrgEntity;
import com.jiyinit.web.core.business.entity.TabCoreUserEntity;
import com.jiyinit.web.core.business.service.NoticeServiceImpl;
import com.jiyinit.web.core.business.service.OrgServiceImpl;
import com.jiyinit.web.core.business.service.ReadMessageServiceImpl;
import com.jiyinit.web.core.business.service.UserServiceImpl;
import com.jiyinit.web.core.business.vo.*;
import com.jiyinit.web.core.common.config.PropertyPlaceholderConfigurer;
import com.jiyinit.web.core.common.util.GlobalsUtils;
import com.jiyinit.web.core.common.util.UserUtil;
import com.jiyinit.web.core.mobile.dto.MobileFileRequest;
import com.jiyinit.web.core.mobile.dto.MobileFileResponse;
import com.jiyinit.web.core.mobile.util.FilesUtil;
import com.jiyinit.web.core.mobile.util.Word2PdfUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.IntrospectionException;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by lr on 2018/1/2.
 */
@Controller
@RequestMapping("/notice")
public class NoticeController {
    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(NoticeController.class);

    @Resource(name = "core.noticeServiceImpl")
    private NoticeServiceImpl noticeService;

    @Resource(name = "core.orgServiceImpl")
    private OrgServiceImpl orgServiceImpl;

    @Resource(name = "send.message")
    private ReadMessageServiceImpl readMessageService;

    @Resource(name = "core.userServiceImpl")
    private UserServiceImpl userService;

    @RequestMapping("tolist")
    public String list(){
        return "notice/list";
    }

    @ResponseBody
    @RequestMapping("findByPage")
    public PagingResult<NoticeVo> findByPage(NoticePageRequest request){
        return noticeService.findByPage(request);
    }

    @RequestMapping("toRead")
    public String toRead(Integer noticeId,Model model){
        model.addAttribute("noticeId",noticeId);
        return "notice/query";
    }
    @ResponseBody
    @RequestMapping("readByPage")
    public PagingResult<SendMessageVo> readByPage(MessagePageRequest request){
        return readMessageService.readByPage(request);
    }

    /**
     * 跳转到新增通知页面
     */
    @RequestMapping("/toAdd")
    public String toAdd(){
        return "/notice/add";
    }

    /**
     * 新增通知接口
     * @param httpServletRequest
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "add")
    public ResponseEntity<ResponseDto> add(HttpServletRequest httpServletRequest){
        NoticeRequest noticeRequest = getJsonToTaskRequest(httpServletRequest);
        if (noticeRequest.getTitle() == null || "".equals(noticeRequest.getTitle())) {
            return new ResponseEntity<>(ResponseDto.responseFail("标题不能为空"), HttpStatus.OK);
        }
        if (noticeRequest.getContent() == null || "".equals(noticeRequest.getContent())) {
            return new ResponseEntity<>(ResponseDto.responseFail("内容不能为空"), HttpStatus.OK);
        }
        if (noticeRequest.getPriority() == null ) {
            return new ResponseEntity<>(ResponseDto.responseFail("优先级不能为空"), HttpStatus.OK);
        }

        int num = noticeService.add(noticeRequest);
        if(num > 0)
            return new ResponseEntity<>( ResponseDto.responseOK(""), HttpStatus.OK);
        return new ResponseEntity<>( ResponseDto.responseFail("新建失败！"), HttpStatus.OK);
    }

    /**
     * 手机端修改通知接口(由于添加时已经推送给相关人员了，所以修改时，人员不可修改)
     * @param httpServletRequest
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "update")
    public ResponseEntity<ResponseDto> update(HttpServletRequest httpServletRequest){
        NoticeRequest noticeRequest = getJsonToTaskRequest(httpServletRequest);
        if (noticeRequest.getNoticeId() == null ) {
            return new ResponseEntity<>(ResponseDto.responseFail("通知Id不能为空"), HttpStatus.OK);
        }
        //只能本人发出的通知
        TabCoreNoticeEntity entity = noticeService.findById(noticeRequest.getNoticeId());
        if(entity.getCreateId().intValue() != noticeRequest.getUserId().intValue())
            return new ResponseEntity<>( ResponseDto.responseFail("没有权限修改"), HttpStatus.OK);

        int num = noticeService.update(noticeRequest);
        if(num > 0)
            return new ResponseEntity<>( ResponseDto.responseOK(""), HttpStatus.OK);
        return new ResponseEntity<>( ResponseDto.responseFail("修改失败！"), HttpStatus.OK);
    }

    /**
     * 通知详情
     * @param httpServletRequest
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "detail")
    public ResponseEntity<ResponseDto> detail(HttpServletRequest httpServletRequest){
        NoticeRequest noticeRequest = getJsonToTaskRequest(httpServletRequest);
        if (noticeRequest.getNoticeId() == null ) {
            return new ResponseEntity<>(ResponseDto.responseFail("通知Id不能为空"), HttpStatus.OK);
        }
        NoticeVo notice = noticeService.detail(noticeRequest.getNoticeId());
        List<NoticeUserVo> list = noticeService.findAlloters(noticeRequest.getNoticeId());
        HashMap<String,Object> result =  new HashMap<String,Object>();
        result.put("notice",notice);
        result.put("alloters",list);

        return new ResponseEntity<>( ResponseDto.responseOK(result), HttpStatus.OK);
    }

    /**
     * 通知删除
     * @param httpServletRequest
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "delete")
    public ResponseEntity<ResponseDto> delete(HttpServletRequest httpServletRequest){
        NoticeRequest noticeRequest = getJsonToTaskRequest(httpServletRequest);
        if (noticeRequest.getNoticeId() == null ) {
            return new ResponseEntity<>(ResponseDto.responseFail("通知Id不能为空"), HttpStatus.OK);
        }

        //只能本人发出的通知
        TabCoreNoticeEntity entity = noticeService.findById(noticeRequest.getNoticeId());
        if(entity.getCreateId().intValue() != noticeRequest.getUserId().intValue())
            return new ResponseEntity<>( ResponseDto.responseFail("没有权限删除"), HttpStatus.OK);

        int  num = noticeService.delete(noticeRequest.getNoticeId(),noticeRequest.getUserId());
        if(num > 0)
            return new ResponseEntity<>( ResponseDto.responseOK(""), HttpStatus.OK);
        return new ResponseEntity<>( ResponseDto.responseFail("删除失败！"), HttpStatus.OK);
    }

    /**
     * 全部
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("findForPage")
    public PagingResult<NoticeVo> findForPage(HttpServletRequest request){
        NoticeRequest noticeRequest = this.getJsonToTaskRequest(request);
        return noticeService.findByPageForMobile(noticeRequest);
    }

    /**
     * 我发布的通知
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("findPublishByPage")
    public PagingResult<NoticeVo> findPublishByPage(HttpServletRequest request){
        NoticeRequest noticeRequest = this.getJsonToTaskRequest(request);
        return noticeService.findPublishByPage(noticeRequest);
    }

    /**
     * 我收到的通知
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("findReceviceByPage")
    public PagingResult<NoticeVo> findReceviceByPage(HttpServletRequest request){
        NoticeRequest noticeRequest = this.getJsonToTaskRequest(request);
        return noticeService.findReceviceByPage(noticeRequest);
    }


    private NoticeRequest getJsonToTaskRequest(HttpServletRequest request){
        String content = (String) request.getAttribute("request_json");
        String logJson = request.getParameter("request_json");
        LogUtil.info(LOGGER, "logJson:{}", logJson);
        NoticeRequest noticeRequest = (NoticeRequest) JsonEntityTransform.json2Object(logJson, NoticeRequest.class);
        return noticeRequest;
    }



    /**
     * 手机端文件上传
     * @param httpServletRequest
     * @return 2019/1/16
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "addFile")
    public ResponseEntity<ResponseDto> addFile(HttpServletRequest httpServletRequest){
        NoticeRequest noticeRequest = getJsonToTaskRequest(httpServletRequest);
        //url在文件上传成功后返回给页面，在传递过来
        if (noticeRequest.getTitle() == null || "".equals(noticeRequest.getTitle())) {
            return new ResponseEntity<>(ResponseDto.responseFail("标题不能为空"), HttpStatus.OK);
        }
        if (noticeRequest.getContent() == null || "".equals(noticeRequest.getContent())) {
            return new ResponseEntity<>(ResponseDto.responseFail("内容不能为空"), HttpStatus.OK);
        }
        if (noticeRequest.getPriority() == null ) {
            return new ResponseEntity<>(ResponseDto.responseFail("优先级不能为空"), HttpStatus.OK);
        }
        if (noticeRequest.getChannel() == null || "".equals(noticeRequest.getChannel())) {
            return new ResponseEntity<>(ResponseDto.responseFail("渠道不能为空"), HttpStatus.OK);
        }

        int num = noticeService.addNotice(noticeRequest);
        if(num > 0)
            return new ResponseEntity<>( ResponseDto.responseOK(""), HttpStatus.OK);
        return new ResponseEntity<>( ResponseDto.responseFail("新建失败！"), HttpStatus.OK);
    }

    /**
     * 上传文件接口
     *
     * @param
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/uploadFile", produces = "application/json; charset=utf-8")
    public ResponseEntity<ResponseDto> fileUpload(HttpServletRequest request,MultipartHttpServletRequest multipartRequest,NoticeRequest noticeRequest) {
        noticeRequest.setUserId(UserUtil.getCurrentUser().getUserId());
        //上传文件
        StringBuilder url=new StringBuilder("");
        //保存项目附件
        if (!Check.isNullObj(multipartRequest)) {
            MultiValueMap<String, MultipartFile> map = multipartRequest.getMultiFileMap();
            List<MultipartFile> multipartFileList = map.get("wordFile");
            for (MultipartFile file : multipartFileList) {
                if (file.getOriginalFilename() != "") {
                     url.append("url="+getFileByMultipartFile(file,request)) ;
                }
            }
        }
        noticeRequest.setFileURL(url.toString());
        int i=noticeService.addNotice(noticeRequest);
        if(i>0){
            return new ResponseEntity<ResponseDto>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("新增失败"), HttpStatus.OK);
    }

    /**
     * 单文件上传
     *@author lcq
     *@date 2018/1/7 10:21
     *@param
     *@return
     */
    public static String getFileByMultipartFile(MultipartFile mFile,HttpServletRequest request) {
        String SAVE_WORD_URL = GlobalsUtils.getValue("SAVE_WORD_URL");
        if(mFile.getSize()<1){
            return null;
        }
        String orgFileName = mFile.getOriginalFilename();
        //将文件保存到本地路径 TEMP_FILE_PATH
         StringBuilder fileName = new StringBuilder(request.getSession().getServletContext().getRealPath("")+"/"+GlobalsUtils.getValue("TEMP_FILE_PATH"));
        fileName.append(orgFileName);
        File file1 = new File(fileName.toString());
        if(!file1.exists()){
            try {
                FilesUtil.createDirectoryAndFile(file1);
                mFile.transferTo(file1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //将文件转为pdf格式
        String inPath =fileName.toString();
        System.out.println(inPath);
        //将文件转为pdf，并返回pdf的路径
        //word转为pdf进行预览
        String outPath =request.getServletContext().getRealPath("/"+SAVE_WORD_URL);
        try {
            Word2PdfUtil.word2pdf(inPath, outPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String name=orgFileName.substring(0,orgFileName.lastIndexOf("."));
        String realPdfUrl=name+".pdf";
        //修改此地址：上线时在配置文件中修改为服务器地址
        String pdfFileName=request.getSession().getServletContext().getRealPath("")+"/"+SAVE_WORD_URL + "/"+realPdfUrl;
        System.out.println("pdfFileName: "+ pdfFileName);
        File file2 = new File(pdfFileName);
        if(!file2.exists()){
            try {
                FilesUtil.createDirectoryAndFile(file2);
                mFile.transferTo(file2);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return realPdfUrl;
    }

    @RequestMapping("/anon/toOrgTree")
    public String toTreeMenu() {
        return "/notice/orgTree";
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/anon/findUsersByOrId")
    public PagingResult findUsersByOrId(HttpServletRequest request,UserRequest userRequest) {
        LogUtil.info(LOGGER, "orgId:{}", userRequest.getOrgId());
        Integer parentId=orgServiceImpl.selectById(userRequest.getOrgId()).getParentId();
        userRequest.setLimit(500000);
        if (parentId==0){
            PagingResult allUsers=userService.findUserByparentId(userRequest);
            return allUsers;
        }else{
            PagingResult pagingResult = userService.findUsersByOrId(userRequest);
            LogUtil.info(LOGGER, "getTotalRecords:{},getTotalPages:{},getRows:{}", pagingResult.getTotalRecords(), pagingResult.getTotalPages(),pagingResult.getRows());
            return pagingResult;
        }
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/anon/findUsersByUserName")
    public PagingResult findUsersByUserName(HttpServletRequest request,UserRequest userRequest) {
        LogUtil.info(LOGGER, "orgId:{}", userRequest.getUserName());
        userRequest.setLimit(500000);
        PagingResult<UserInfoVo> pagingResult = userService.getUserInfoListByUserName(userRequest);
        return pagingResult;
        }







}
